<script lang="ts" setup>
import type { Dict } from '@croco/framework/types';

import { onBeforeMount, ref } from 'vue';

import { Page } from '@croco/framework/libraries';

import { getDictTrim } from '#/api';
import { service } from '#/api/request';
import { DataTable } from '#/components/data-table';

import { useTable } from './data';
import Edit from './edit.vue';

defineOptions({ name: 'SystemConfig' });

const dataTableRef = ref<InstanceType<typeof DataTable>>();
const editRef = ref<InstanceType<typeof Edit>>();
const enums = reactive<{
    type: Array<Dict> | undefined;
}>({
    type: undefined,
});
const columns = useTable(enums, ({ code, scope }) => {
    switch (code) {
        case 'edit': {
            onEdit(scope.row);
            break;
        }
        case 'remove': {
            onDelete([scope.row]);
            break;
        }
        default: {
            break;
        }
    }
});

// 表单
function onEdit(row?: any) {
    editRef.value?.open({
        data: row,
        success: dataTableRef.value?.refresh,
    });
}

function onReload() {
    service.confirm({
        message: `确定重置缓存?`,
        url: '/system/config/reload',
    });
}

// 删除
function onDelete(rows: { code: number; name: string }[]) {
    const names = rows.map((item) => item.name);
    const codes = rows.map((item) => item.code);
    service.confirm({
        message: `确定对参数配置[${names.join(',')}]进行${names.length === 1 ? '删除' : '批量删除'}操作?`,
        url: '/system/config',
        data: { code: codes },
        success: dataTableRef.value?.refresh,
    });
}

onBeforeMount(() => {
    // 获取字典数据
    getDictTrim('sys_yes_no').then((rs) => {
        enums.type = rs[0] ?? [];
    });
});
</script>
<template>
    <Page auto-content-height>
        <DataTable ref="dataTableRef" :columns="columns" api="/system/config" selection select-on-row-click>
            <template #extra="{ selections }">
                <el-button v-auth="'system:config:add'" @click="onEdit()" />
                <el-button v-auth="'system:config:remove'" @click="onDelete(selections)" :disabled="selections.length <= 0" type="danger" />
                <el-button v-auth="'system:config:reload'" @click="onReload()" type="warning" />
            </template>
        </DataTable>

        <Edit ref="editRef" :enums="enums" />
    </Page>
</template>
